package com.example.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.Constants;
import com.example.springboot.controller.dto.UserDTO;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.IUserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    //抛出异常日志
    private static final Log LOG = Log.get();

    @Override
    public UserDTO login(UserDTO userDto) {
        User one = getUserInfo(userDto);
        if (one != null) {
            //从one 复制 数据 到userDto
            BeanUtil.copyProperties(one, userDto, true); //true忽略大小写
            //设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDto.setToken(token);

            return userDto;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }

    }

    //注册
    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if(one == null){
            one = new User();
            //复制属性到 one
            BeanUtil.copyProperties(userDTO, one, true); //true忽略大小写
            save(one);  //把copy完后的用户对象存储到数据库里面
        }else {
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;
    }

    private User getUserInfo(UserDTO userDTO) {
        //到数据库查询泛型对象必须是实体类User
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());

//        List<User> list = list(queryWrapper); //数据库有相同数据可以直接登录
//        return list.size() != 0;

        //如果数据库中有相同的username与password就会抛出异常
        User one;
        try {
            one = getOne(queryWrapper); //从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }
}



